<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header" class="clearfix">
        <span v-if="qnewForm.id===null">试题录入</span>
        <span v-else>试题修改</span>
      </div>
      <!-- 主体 -->
      <div>
        <!-- 表单 -->
        <el-form :model="qnewForm" :rules="qnewrules" ref="qnewForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="qnewForm.subjectID" placeholder="请选择" @change="subjectIDChange">
              <el-option v-for="item in simpleList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="qnewForm.catalogID" placeholder="请选择" @change="changeAA">
              <el-option v-for="item in directorysList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="qnewForm.enterpriseID" placeholder="请选择" @change="changeBB">
              <el-option v-for="item in companysList" :key="item.id" :label="item.company" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city" class="cityselect">
            <el-select v-model="qnewForm.province" placeholder="请选择" @change="cityChange">
              <el-option v-for="(item,index) in provinces" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
            <el-select v-model="qnewForm.city" placeholder="请选择" style="width:50%;" @change="changeCC">
              <el-option v-for="(item,index) in citys" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="qnewForm.direction" placeholder="请选择" @change="changeDD">
              <el-option v-for="(item,index) in direction" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="qnewForm.questionType">
              <el-radio :label="'1'">单选</el-radio>
              <el-radio :label="'2'">多选</el-radio>
              <el-radio :label="'3'">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="qnewForm.difficulty">
              <el-radio :label="'1'">简单</el-radio>
              <el-radio :label="'2'">一般</el-radio>
              <el-radio :label="'3'">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <quill-editor v-model="qnewForm.question" ref="myQuillEditora" :options="editorOption"
              @blur=changeAQuillEditor>
            </quill-editor>
            <el-input v-model="qnewForm.question" ref="myQuillEditoraa" style="display:none"></el-input>
          </el-form-item>
          <el-form-item label="选项：" prop="options" v-if="qnewForm.questionType!='3'">
            <!-- 单选 -->
            <div v-if="qnewForm.questionType=='1'">
              <el-radio-group v-model="qnewForm.chioe">
                <div v-for="item in qnewForm.options" :key="item.id" style="margin-bottom:20px" class="options">
                  <el-radio :label="item.code">{{item.code+'：'}}</el-radio>
                  <el-input v-model="item.title" style="width:240px"></el-input>
                  <!-- 上传图片 -->
                  <div class="avatar-uploader">
                    <el-upload action="https://jsonplaceholder.typicode.com/posts/" :on-preview="picPreview"
                      :on-remove="picRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList"
                      list-type="picture-card" :on-change=picChange>
                      <el-button size="small" type="text">上传图片</el-button>
                    </el-upload>
                  </div>
                </div>
              </el-radio-group>
            </div>
            <!-- 多选 -->
            <div v-if="qnewForm.questionType=='2'">
              <el-checkbox-group v-model="qnewForm.chioes">
                <div v-for="item in qnewForm.options" :key="item.id" style="margin-bottom:20px" class="options">
                  <el-checkbox :label="item.code">{{item.code+'：'}}</el-checkbox>
                  <el-input v-model="item.title" style="width:240px"></el-input>
                  <!-- 上传图片 -->
                  <div class="avatar-uploader">
                    <el-upload action="https://jsonplaceholder.typicode.com/posts/" :on-preview="picPreview"
                      :on-remove="picRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList"
                      list-type="picture-card" :on-change=picChange>
                      <el-button size="small" type="text">上传图片</el-button>
                    </el-upload>
                  </div>
                </div>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="danger" :disabled="qnewForm.questionType!=2" @click="addchioe">+ 增加选项与答案
            </el-button>
            <el-button size="small" type="primary" icon="el-icon-delete" :disabled="qnewForm.questionType!=2"
              v-if="num>69" @click="subchioe">
              减少选项与答案
            </el-button>
          </el-form-item>
          <el-form-item label="解析视频：" prop="videoURL">
            <el-input v-model="qnewForm.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor v-model="qnewForm.answer" ref="myQuillEditorb" :options="editorOption"
              @blur=changeBQuillEditor>
            </quill-editor>
            <el-input v-model="qnewForm.answer" ref="myQuillEditorbb" style="display:none"></el-input>
          </el-form-item>
          <el-form-item label="题目备注：" prop="remarks">
            <el-input type="textarea" :rows="3" v-model="qnewForm.remarks">
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签：" prop="tag">
            <el-select v-model="qnewForm.tag" multiple filterable allow-create default-first-option
              placeholder="请选择试题标签" @change="changeEE">
              <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="qnewForm.id===null" type="primary" size="samll" @click="addNewQuestion">确认提交</el-button>
            <el-button v-else type="success" size="samll" @click="editQuestion">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
// 详情列表 ,修改,添加 ,add
import { detail as questionsDetail, update, add } from '@/api/hmmm/questions.js'
// 请求学科下拉列表 , 学科id找名字
import { simple } from '@/api/hmmm/subjects.js'
// 选中学科请求二级目录列表
import { simple as directorysList } from '@/api/hmmm/directorys.js'
// 企业下拉列表
import { list as companysList } from '@/api/hmmm/companys.js'
// 请求试题类型,难度,方向下拉列表
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
// 请求城市,地区下拉列表
import { provinces, citys } from '@/api/hmmm/citys.js'
// 请求标签列表
import { simple as tagsList } from '@/api/hmmm/tags.js'
export default {
  data () {
    return {
      // 表单规则
      qnewrules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        question: [{ required: true, message: '请填写题干', trigger: 'blur' }],
        // videoURL: [{ required: true, message: '请填写解析视频', trigger: 'blur' }],
        answer: [{ required: true, message: '请填写答案解析', trigger: 'blur' }],
        // remarks: [{ required: true, message: '请填写题目备注', trigger: 'blur' }],
        tag: [{ required: true, message: '请填写试题标签', trigger: 'blur' }]
      },
      // 用户填写的表单数据
      qnewForm: {
        id: null,
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
        tag: [],
        chioe: '',
        chioes: []
      },
      simpleList: [], // 学科数据
      directorysList: [], // 二级目录数据
      companysList: [], // 企业数据
      questionType, // 试题类型
      difficulty, // 难度
      direction, // 方向
      citys: [], // 地区
      tagsList: [], // 标签数据
      // 富文本配置
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 上传图片、上传视频
          ]
        }
      },
      // 上传图片的数据
      imgUrl: '',
      // 上传图片URL
      // picAction: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片
      fileList: [],
      // 选项的ASCII码 默认第一个是A
      num: 65
    }
  },
  created () {
    // 点击修改跳转获得的表单数据
    this.getFormList()
    // 初始化学科数据
    this.getSimpleList()
    // 初始化企业下拉数据
    this.getCompanysList()
    // 默认添加ABCD四条数据
    for (let i = 0; i < 4; i++) {
      this.qnewForm.options.push({
        code: String.fromCharCode(this.num),
        title: '',
        img: '',
        isRight: ''
      })
      this.num++
    }
  },
  methods: {
    // route传递的id请求数据
    async getFormList () {
      this.qnewForm.id = this.$route.query.id || null
      // 判断是否携带跳转参数
      if (this.$route.query.id !== undefined) {
        // 传递id获取试题详情
        const res = await questionsDetail({ id: this.qnewForm.id })
        console.log('route的数据', res.data)
        // 处理tags  绑定的是tag  后台tags
        res.data.tag = res.data.tags.split(',')
        // 处理选项绑定的值
        // 单选  遍历options  获取isRight为1的code绑定到group上 让其默认选中
        let chioe = ''
        if (res.data.questionType === '1') {
          res.data.options.forEach(item => {
            if (item.isRight === 1) {
              chioe = item.code
            }
          })
        }
        // 多选 同理
        const chioes = []
        if (res.data.questionType === '2') {
          res.data.options.forEach(item => {
            if (item.isRight === 1) {
              chioes.push(item.code)
            }
          })
        }
        res.data.chioe = chioe
        res.data.chioes = chioes
        // 判断options长度 获取下一个选项的code值
        this.num = res.data.options.length + 65
        // 遍历options 为其item增加sortId属性 值为code的ASCII码转为数字
        res.data.options.forEach(item => {
          item.sortId = item.code.charCodeAt()
        })
        // console.log(res.data.options.sort(this.sortBy('sortId', true)))
        // 根据sortId 排序
        res.data.options.sort(this.sortBy('sortId', true))
        // 处理后的数据赋值到data里
        this.qnewForm = res.data
        console.log('处理后的数据', this.qnewForm)
        // 初始化目录下拉数据
        this.getDetailList()
        // 初始化标签下拉数据
        this.getTagsList()
        // console.log('城市/地区', this.provinces, this.citys)
        // 富文本编辑器神坑处理
        this.$nextTick(function () {
          this.$refs.myQuillEditora.quill.enable(true)
          this.$refs.myQuillEditora.quill.blur()
          this.$refs.myQuillEditorb.quill.enable(true)
          this.$refs.myQuillEditorb.quill.blur()
        })
      }
    },
    // 学科数据
    async getSimpleList () {
      const res = await simple()
      console.log('学科下拉数据', res)
      this.simpleList = res.data
    },
    // 二级目录数据
    async getDetailList () {
      const res = await directorysList({ subjectID: this.qnewForm.subjectID })
      console.log('目录下拉数据', res)
      this.directorysList = res.data
    },
    // 企业数据
    async getCompanysList () {
      const res = await companysList()
      console.log('企业下拉数据', res)
      this.companysList = res.data.items
    },
    // 学科下拉改变
    subjectIDChange () {
      // 获取目录
      this.getDetailList()
      // 获取标签
      this.getTagsList()
      this.$refs.qnewForm.validateField('subjectID')
    },
    // 城市选择改变
    cityChange (city) {
      // 获取地区
      this.citys = citys(city)
      this.$refs.qnewForm.validateField('city')
    },
    // 标签数据
    async getTagsList () {
      const res = await tagsList({ subjectID: this.qnewForm.subjectID })
      console.log('标签下拉数据', res)
      this.tagsList = res.data
    },
    // 富文本预校验
    changeAQuillEditor () {
      this.$refs.qnewForm.validateField('question')
      // this.$refs.myQuillEditoraa.validate() // this.qnewForm.question
    },
    // 富文本预校验
    changeBQuillEditor () {
      this.$refs.qnewForm.validateField('answer')
      // this.$refs.myQuillEditorbb.validate()// this.qnewForm.
    },
    // 点击按钮添加试题
    addNewQuestion () {
      // 预校验
      this.$refs.qnewForm.validate(async (valid) => {
        if (valid) {
          const form = { ...this.qnewForm }
          // 处理tags
          form.tags = form.tag.join(',')
          // 通过选项绑定的值查找code 查到到就让isRight属性改成1
          console.log('发送的数据', form)
          if (form.questionType === '1') {
            form.options.forEach(item => {
              if (item.code === form.chioe) {
                item.isRight = 1
              }
            })
          } else if (form.questionType === '2') {
            form.options.forEach(item => {
              form.chioes.forEach(item1 => {
                if (item.code === item1) {
                  item.isRight = 1
                }
              })
            })
          }
          // 发送请求 参数为处理后的数据对象
          const res = await add(form)
          console.log(res)
          // 状态码判断
          if (res.request.status !== 200) return this.$message.error('添加失败')
          this.$message.success('添加成功')
          // 跳转
          this.$router.push('/questions/list')
        } else {
          this.$message.warning('亲 ~ 请填写完整试题信息')
          return false
        }
      })
    },
    // 点击按钮修改试题
    editQuestion () {
      // 预校验
      this.$refs.qnewForm.validate(async (valid) => {
        if (valid) {
          const form = { ...this.qnewForm }
          // 处理tags
          form.tags = form.tag.join(',')
          // 通过选项绑定的值查找code 查到到就让isRight属性改成1
          console.log('发送的数据', form)
          if (form.questionType === '1') {
            form.options.forEach(item => {
              if (item.code === form.chioe) {
                item.isRight = 1
              } else if (item.code !== form.chioe) {
                item.isRight = 0
              }
            })
          } else if (form.questionType === '2') {
            form.options.forEach(item => {
              item.isRight = form.chioes.some(item1 => item1 === item.code)
            })
          }
          // 发送请求 参数为处理后的数据对象
          const res = await update(form)
          console.log(res)
          // 状态码判断
          if (res.request.status !== 200) return this.$message.error('修改失败')
          this.$message.success('修改成功')
          // 跳转
          this.$router.push('/questions/list')
        } else {
          this.$message.warning('亲 ~ 请填写完整试题信息')
          return false
        }
      })
    },
    // 上传图片
    // 超过上传限制回调
    handleExceed (files) {
      console.log(files)
      this.$message.warning('当前限制选择 1 张图片')
    },
    // 预览
    picPreview (a, b) {
      console.log(a, b)
    },
    // 关闭
    picRemove (a, b) {
      console.log(a, b)
    },
    // 上传成功
    picSucess (a, b) {
      console.log(a, b)
    },
    //
    picChange (a, b) {
      console.log(a, b)
    },
    // 点击按钮增加试题选项
    addchioe () {
      // fromCharCode()
      this.qnewForm.options.push({
        code: String.fromCharCode(this.num),
        title: '',
        img: '',
        isRight: ''
      })
      this.num++
    },
    // 点击减少
    subchioe () {
      this.qnewForm.options.pop()
      this.num--
    },
    // 后台返回数据 选项顺序打乱bug  通过code的ASCII转数字升序排序
    sortBy (attr, rev) {
      // 第二个参数没有传递 默认升序排列
      if (rev === undefined) {
        rev = 1
      } else {
        rev = (rev) ? 1 : -1
      }
      return function (a, b) {
        a = a[attr]
        b = b[attr]
        if (a < b) {
          return rev * -1
        }
        if (a > b) {
          return rev * 1
        }
        return 0
      }
    },
    // 校验
    changeAA () {
      this.$refs.qnewForm.validateField('catalogID')
    },
    changeBB () {
      this.$refs.qnewForm.validateField('enterpriseID')
    },
    changeCC () {
      this.$refs.qnewForm.validateField('city')
    },
    changeDD () {
      this.$refs.qnewForm.validateField('direction')
    },
    changeEE () {
      this.$refs.qnewForm.validateField('tag')
    }
  },
  computed: {
    provinces // 城市数据
  },
  mounted () {
    // 富文本自动获取焦点bug解决  禁用
    if (this.$route.query.id !== undefined) {
      this.$refs.myQuillEditora.quill.enable(false)
      this.$refs.myQuillEditorb.quill.enable(false)
    }
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 10px;
}
.container {
  padding: 10px;
}
.el-select,
.el-input,
/deep/ .el-textarea__inner {
  width: 400px;
}

/deep/ .cityselect .el-select {
  width: 198px !important;
  margin-right: 2px;
}
.quill-editor {
  height: 200px;
  max-width: 1000px;
  margin-bottom: 70px;
}

/deep/ .options {
  .el-radio {
    margin-right: 0;
  }
  .el-input {
    margin-right: 30px;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    width: 100px;
    height: 60px;
  }
}
.avatar-uploader {
  margin-left: 4px;
  display: inline-block;
  vertical-align: middle;
}
/deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
  img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
}
.el-checkbox {
  width: 50px;
}
</style>
